package com.project.controller;

import com.github.pagehelper.PageInfo;
import com.project.bean.LinkBean;
import com.project.service.ILinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("link")
public class LinkController {
    @Autowired
    private ILinkService service;

    @RequestMapping("findAll")
    public void findAll(Integer pageNo,HttpServletResponse resp) throws IOException {
        int num = pageNo == null? 1 : pageNo;
        resp.setContentType("text/html;charset=utf-8");
        PageInfo<LinkBean> linkList = service.findAll(num);
        String str = "<table border='1' width='60%'>";
        str += "<thead><tr><th>姓名</th><th>生日</th><th>电话</th><th>操作</th></tr></thead>";
        str += "<tbody>";
        for (LinkBean link : linkList.getList()){
            str += "<tr><td>"+link.getName()+"</td><td>"+link.getBirthday()+"</td><td>"+
                    link.getPhone()+"</td>"+"<td><a href='/link/del?id="+link.getId()+"'>删除</a>" +
                    "<a href='/link/findById?id="+link.getId()+"'>修改</a></td></tr>";
        }
        str += "</tbody></table>";
        str += "<a href='/html/addLink.html'>添加</a><br>";
        int[] page = linkList.getNavigatepageNums();
        for (int i=1;i<=page.length;i++){
            str += " <a href='/link/findAll?pageNo="+i+ "'>"+ i +"</a> ";
        }
        resp.getWriter().print(str);
    }
    @RequestMapping("add")
    public String add(LinkBean link){
        service.add(link);
        return "redirect:/link/findAll";
    }
    @RequestMapping("del")
    public String del(int id){
        service.del(id);
        return "redirect:/link/findAll";
    }
    @RequestMapping("findById")
    public void findById(int id,HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        LinkBean lin = service.findById(id);

        String str ="<from action='/link/update'>";
        str += "<input type='hidden' name='id' value='"+id+"'>";
        str += "姓名："+lin.getName()+"<br>";
        str += "生日："+lin.getBirthday()+"<br>";
        str += "电话：<input type='text' name='phone' value='"+lin.getPhone()+"'><br>";
        str += "<input type='submit' value='修改'>";
        str += "</from>";
        resp.getWriter().print(str);
    }
    @RequestMapping("update")
    public String update(int id,String phone){
        service.update(id,phone);
        return "redirect:/link/findAll";
    }
}
